<?php
/**
 * @author fld 2021-09-13
 * @desc 上传业务类
 */
namespace App\Service\Image;


use Illuminate\Http\Request;

class UploadService
{
    public function __construct()
    {

    }
    /**
     * @author fld 2021-09-13
     * @desc 上传图片
     * @param Request $request
     * @param String $file_name
     * @return number[]|string[]|number[]|unknown[]|string[]
     */
    public function uploadImg(Request $request, String $file_name){
        $file = $request->file($file_name);
        if($request->hasFile($file_name) && $file->isValid()){
            $data = [];
            //图片扩展名
            $extension = $file->getClientOriginalExtension();
            //图片原始名称
            $original_name = $file->getClientOriginalName();
            //图片上传缓存的绝对路径
            $path = $file->getRealPath();
            //图片大小
            $file_size = $file->getSize();
            $max_file_size = env('MAX_IMAGE_FILE_SIZE');
            if($file_size > $max_file_size){
                return ['code'=>1,'message'=>'上传图片不能超过1M'];
            }
            //新图片名称
            $new_filename = date('YmdHis').rand(1000,9999).'.'.$extension;
            $new_path = 'upload/image/'.date('Ymd');
            if(!is_dir($new_path)){
                mkdir($new_path, 0777 );
            }
            $path = $file->move($new_path,$new_filename);
            if($path){
                $path = str_ireplace('\\', '/', $path);
                return ['code'=>0, 'original_name'=>$original_name, 'extension'=>$extension , 'new_path'=>$path];
            }else{
                return ['code'=>1,'message'=>'上传图片失败'];
            }
        }else{
            return ['code'=>1,'message'=>'上传图片不存在'];
        }
    }
}